package ${initProjectVo.packageName}.security;

import ${initProjectVo.packageName}.entity.Permission;
import ${initProjectVo.packageName}.service.IRoleUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Supplier;

@Component
public class AccessAuthorizationManager implements AuthorizationManager<HttpServletRequest> {

    @Autowired
    private IRoleUserService roleUserService;


    @Override
    public void verify(Supplier<Authentication> authentication, HttpServletRequest object) {
        AuthorizationDecision decision = check(authentication, object);
        if (decision != null && !decision.isGranted()) {
            throw new AccessDeniedException("访问受限");
        }

    }

    @Override
    public AuthorizationDecision check(Supplier<Authentication> authentication, HttpServletRequest request) {
        Object userInfo = authentication.get().getPrincipal();
        boolean hasPermission  = false;
        if (userInfo instanceof UserDetails) {

            MyUserDetails principal = (MyUserDetails) authentication.get().getPrincipal();
            //获取资源
            Set<String> urls = new HashSet();

            List<Permission> permissionList = roleUserService.getPermissionForUser(principal.getId());
            permissionList.forEach(item->{
                urls.add(item.getRouterUrl());
            });
            AntPathMatcher antPathMatcher = new AntPathMatcher();
            for (String url : urls) {
                if (antPathMatcher.match(url, request.getRequestURI())) {
                    hasPermission = true;
                    break;
                }
            }
        }
        return new AuthorizationDecision(hasPermission);
    }
}
